package sk.tramtatiri.pages.users;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.markup.html.form.AjaxFallbackButton;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

import sk.tramtatiri.MySession;
import sk.tramtatiri.core.IConstants;
import sk.tramtatiri.data.dao.interfaces.FriendshipDao;
import sk.tramtatiri.data.dao.interfaces.UserDao;
import sk.tramtatiri.data.dataobjects.Friendship;
import sk.tramtatiri.data.dataobjects.User;

public class UserSearchResultPage extends UserPageTemplate {

	@SpringBean
	private UserDao userDao;
	
	@SpringBean
	private FriendshipDao friendshipDao;
	
	private List<User> userList = new ArrayList<User>();

	public UserSearchResultPage(final PageParameters pageParams) {
		String name = pageParams.getString("name");
		userList = userDao.findAllByNameExceptMe(((MySession)getSession()).getUserID(), name);
		
		add(new ListView<User>("rows", userList) {
		    protected void populateItem(ListItem item) {
		        final User user = (User) item.getModelObject();
		        item.add(new Label("nickname", user.getNickName()));
		        item.add(new Label("useremail", user.getEmail()));
		        
		        item.add(new Link("requestBtn"){
					@Override
					public void onClick() {
						Friendship friendship = new Friendship();
						friendship.setUser(userDao.load(((MySession)getSession()).getUserID()));
						friendship.setFriend(user);
						friendship.setUserId(((MySession)getSession()).getUserID());
						friendship.setFriend_id(user.getId());
						friendship.setSharedStats(1);
						friendshipDao.save(friendship);
						userDao.load(((MySession)getSession()).getUserID()).getFriendships().add(friendship);
						
						friendship = new Friendship();
						friendship.setUser(user);
						friendship.setFriend(userDao.load(((MySession)getSession()).getUserID()));
						friendship.setUserId(user.getId());
						friendship.setFriend_id(((MySession)getSession()).getUserID());
						friendship.setSharedStats(0);
						friendshipDao.save(friendship);
						user.getFriendships().add(friendship);
					}
				});
		    }
		});
		
		
	}
	
	@Override
	public String getPageTitle() {
		return IConstants.PAGE_NAME + " - Search results";
	}

}
